package com.supostacks.application.application.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.supostacks.application.application.ICardKeyApplication;
import com.supostacks.ase.PasswordUtils;
import com.supostacks.domain.service.ICardKeyService;
import com.supostacks.domain.vo.BaseVo;
import com.supostacks.domain.vo.CardKeyVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class CardKeyApplicationImpl implements ICardKeyApplication {
    @Resource
    private ICardKeyService cardKeyService;

    @Override
    public String insert(JSONObject data) {
        CardKeyVo cardKeyVo = JSONObject.toJavaObject(data, CardKeyVo.class);
        return cardKeyService.insert(cardKeyVo);
    }

    @Override
    public void deleteById(String id) {
        cardKeyService.deleteById(id);
    }

    @Override
    public String updateById(JSONObject data) {
        CardKeyVo cardKeyVo = JSONObject.toJavaObject(data, CardKeyVo.class);
        return cardKeyService.updateById(cardKeyVo);
    }

    @Override
    public CardKeyVo selectById(String id) {
        return cardKeyService.selectById(id);
    }


    @Override
    public List<BaseVo> selectList(JSONObject options) {
        List<CardKeyVo> cardKeyVos = cardKeyService.selectList(options);
        return new ArrayList<>(cardKeyVos);
    }

    @Override
    public JSONObject selectByPage(JSONObject options, int pageNo, int pageSize) {
        return cardKeyService.selectByPage(options, pageNo, pageSize);
    }

    @Override
    public List<BaseVo> search(JSONObject option) {
        return Collections.emptyList();
    }

    @Override
    public void generateCard(int count, String type, String secretKey) {
        for (int i = 0; i < count; i++) {
            String nanoId = IdUtil.nanoId();

            // 加密明文： type:卡密类型，nanoId:卡密ID
            String key = type + "#=#" + nanoId;
            String encrypt = PasswordUtils.encrypt(key, secretKey);

            CardKeyVo cardKeyVo = CardKeyVo.builder().codeKey(encrypt)
                    .keyType(type).
                    status("未使用").id(nanoId).createTime(new Date()).build();

            cardKeyService.insert(cardKeyVo);
        }
    }

    @Override
    public String decryptCode(String code, String secretKey) {
        try {
            return PasswordUtils.decrypt(code, secretKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public CardKeyVo selectCardKeyByCode(String code) {
        return cardKeyService.selectCardKeyByCode(code);
    }
}
